# -*- coding: UTF-8 -*-
import json
import time
import hashlib
import requests
import uuid
import logging, pdb, datetime
from urllib.parse import quote
from user.models import UserInfo, VSession
from branch.models import *

class DataCheck():
    # 模块验证数据是否合法
    def teacherId(self, requestParam):
        # 设置初始验证值
        isValidOk = True
        errMsg = ''
        # 验证用户id必须存在
        user = Teacher.objects.filter(pk=requestParam['teacherId'])
        if isValidOk and (not user.exists()):
            errMsg = 'teacherId Error'
            isValidOk = False
        return isValidOk, errMsg

    def IntCheck(self, requestParam):
        # limit 和 page 均大于0
        # 设置初始验证值
        isValidOk = True
        errMsg = ''
        if (isValidOk and requestParam['maxItem'] < 1):
            errMsg = 'limit Error'
            isValidOk = False
        if (isValidOk and requestParam['page'] < 1):
            errMsg = 'page Error'
            isValidOk = False
        return isValidOk, errMsg

    def onlineClassIdList(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证onlineClassId必须存在
        for i in requestParam['onlineClassId']:
            onlineClass = OnlineClass.objects.filter(pk=i)
            if isValidOk and (not onlineClass.exists()):
                errMsg = 'onlineClassId Error'
                isValidOk = False
            return isValidOk, errMsg

    def onlineClassIdsim(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证onlineClassId必须存在
        onlineClass = OnlineClass.objects.filter(pk=requestParam['onlineClassId'])
        if isValidOk and (not onlineClass.exists()):
            errMsg = 'onlineClassId Error'
            isValidOk = False
        return isValidOk, errMsg

    def clientTypeid(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证onlineClassId必须存在
        if isValidOk and (not (requestParam['clientType'] in [0, 1, 2])):
            errMsg = 'clientTypeid Error'
            isValidOk = False
        return isValidOk, errMsg

    def userType(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证userType必须存在
        if isValidOk and (not (requestParam['userType'] in ['student', 'teacher', 'employee', 'admin'])):
            errMsg = 'userType Error'
            isValidOk = False
        return isValidOk, errMsg

    def getLocalToken(self):
        m = hashlib.md5()
        m.update(bytes(str(time.time()), encoding='utf-8'))
        return m.hexdigest()[0:20]

    def tokenCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        userInfo = UserInfo.objects.filter(vsession__token=requestParam['token'])
        if isValidOk and (not userInfo.exists()):
            errMsg = 'token Error'
            isValidOk = False
        # if isValidOk and (requestParam['token'] != sessionList[0].token):
        #     errMsg = 'match Error'
        #     isValidOk = False
        else:
            userInfo = userInfo[0]   
        
        return isValidOk, errMsg

    # 用户没有练习记录
    def musicPractice_Check(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        userInfo = UserInfo.objects.get(vsession__token=requestParam['token'])
        musicpractice = musicPractice.objects.filter(player_id = userInfo.id)
        if isValidOk and (not musicpractice.exists()):
            errMsg = 'no record of practice'
            isValidOk = False
        # else:
        #     userInfo = userInfo[0]   
        
        return isValidOk, errMsg

    # 由token得到user
    def getUser(self, requestParam):
        # pdb.set_trace()
        user = UserInfo.objects.get(vsession__token=requestParam['token'])
        return user

    # 判断该用户是否为学生
    def studentCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        userInfo = UserInfo.objects.get(token=requestParam['token'])
        if userInfo.userType != u'student':
            errMsg = 'not student'
            isValidOk = False
        return isValidOk, errMsg

    # 验证FavorId是否存在
    def favorIDCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        userInfo = UserInfo.objects.get(vsession__token=requestParam['token'])
        favorID = Favorites.objects.filter(userInfo_id = userInfo.id)
        if isValidOk and (not favorID.exists()):
            errMsg = 'This user has no favorites'
            isValidOk = False

        return isValidOk, errMsg


    # 用户存在收藏夹，但该乐谱已经被收藏了
    def music_isrecordCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # pdb.set_trace()
        userInfo = UserInfo.objects.get(vsession__token=requestParam['token'])
        favorites = Favorites.objects.get(userInfo_id = userInfo.id)
        music_mid_favor = Favorites_mid_MusicInfo.objects.get(favorites_id = favorites.id)
        musicid = music_mid_favor.musicID_id
        if isValidOk and (musicid == requestParam['musicId']):
            errMsg = 'The music has been collected'
            isValidOk = False
        return isValidOk, errMsg

    # 用户存在收藏夹，但该乐谱还没有被收藏
    def music_isnot_recordCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # pdb.set_trace()
        userInfo = UserInfo.objects.get(vsession__token=requestParam['token'])
        favorites = Favorites.objects.get(userInfo_id = userInfo.id)
        music_mid_favor = Favorites_mid_MusicInfo.objects.filter(favorites_id = favorites.id)
        musicId = music_mid_favor.filter(musicID_id = requestParam['musicId'])
        if isValidOk and (not musicId.exists()):
            errMsg = 'The music has not been collected'
            isValidOk = False
        return isValidOk, errMsg

    # 验证musicId是否存在
    def musicIdCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        musicId = MusicInfo.objects.filter(id = requestParam['musicId'])
        if isValidOk and (not musicId.exists()):
            errMsg = 'musicId not exist'
            isValidOk = False

        return isValidOk, errMsg

    # 验证乐谱的时间轴信息是否存在
    def musicId_timelineCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        musicId = TimeLine.objects.filter(musicId = requestParam['musicId'])
        if isValidOk and (not musicId.exists()):
            errMsg = 'musicId not exist, so not timeline'
            isValidOk = False
        return isValidOk, errMsg

    # 该乐谱是否在Favorites_mid_MusicInfo有记录
    def musicID_favorCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        musicId = Favorites_mid_MusicInfo.objects.filter(musicID_id = requestParam['musicId'])
        if isValidOk and (not musicId.exists()):
            errMsg = 'musicId not exist'
            isValidOk = False

        return isValidOk, errMsg

    # 验证某用户是否有对应的musicId的练习记录
    def user_musicIdCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        musicId = musicPractice.objects.filter(music_id = requestParam['musicId'])
        if isValidOk and (not musicId.exists()):
            errMsg = 'the user have not this music practice'
            isValidOk = False

        return isValidOk, errMsg

    # 验证该用户是否已经选择等级（默认等级为0）
    def selectlevel_Check(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        userInfo = UserInfo.objects.get(vsession__token=requestParam['token'])
        level = userInfo.level
        if isValidOk and (level == 0):
            errMsg = 'You have not chosen the level of practice yet'
            isValidOk = False

        return isValidOk, errMsg


    # pdb.set_trace()
    # 验证收藏夹名称是否存在
    def favorNameCheck(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证token必须存在
        # pdb.set_trace()
        favorList = Favorites.objects.filter(favorName = requestParam['favorName'])
        if isValidOk and (favorList.exists()):
            errMsg = 'favorName already exist'
            isValidOk = False

        return isValidOk, errMsg



    def examId(self, requestParam):
        # 设置初始验证值
        isValidOk = True
        errMsg = ''
        # 验证examid必须存在
        exam = ExamQuestion.objects.filter(pk=requestParam['examId'])
        if isValidOk and (not exam.exists()):
            errMsg = 'examId Error'
            isValidOk = False
        return isValidOk, errMsg

    def getTeacherByClass(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        count = 0
        if isValidOk and requestParam['classType'] != '':
            count += 1
            if isValidOk and (not requestParam['classType'] in ['ALL', '听力', '写作', '阅读', '口语', '综合']):
                errMsg = "classType Error"
                isValidOk = False
        if isValidOk and requestParam['type'] != '':
            count += 1
            if isValidOk and (not requestParam['type'] in ['ALL', 'MY']):
                errMsg = "type Error"
                isValidOk = False
        if isValidOk and (requestParam['startDate'] != '' and requestParam['stopDate'] != ''):
            count += 1
            if isValidOk and (not(requestParam['startDate'] < requestParam['stopDate'])):
                errMsg = "time Error"
                isValidOk = False
        elif isValidOk and (not(requestParam['startDate'] == '' or requestParam['stopDate'] == '')):
            errMsg = "time Error"
            isValidOk = False
        if isValidOk and count == 0:
            errMsg = "all empty count Error"
            isValidOk = False
        return isValidOk, errMsg

    def classSearch(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        count = 0
        if requestParam['classType'] != '':
            count += 1
            if isValidOk and (not requestParam['classType'] in ['ALL', '听力', '写作', '阅读', '口语', '综合']):
                errMsg = "classType Error"
                isValidOk = False
        if isValidOk and requestParam['type'] != '':
            count += 1
            if isValidOk and (not requestParam['type'] in ['ALL', 'MY']):
                errMsg = "type Error"
                isValidOk = False
        if isValidOk and (requestParam['startDate'] != '' and requestParam['stopDate'] != ''):
            count += 1
            if isValidOk and (not(requestParam['startDate'] < requestParam['stopDate'])):
                errMsg = "time Error"
                isValidOk = False
        elif isValidOk and (not(requestParam['startDate'] == '' or requestParam['stopDate'] == '')):
            errMsg = "time Error"
            isValidOk = False
        # if isValidOk and (not requestParam['teacherName'] == ''):
        #     count += 1
        #     if isValidOk and requestParam['teacherName'] != '-1':
        #         验证用户id必须存在
                # user = Teacher.objects.filter(pk=requestParam['teacherName'])
                # if isValidOk and (not user.exists()):
                #     errMsg = 'teacherName Error'
                #     isValidOk = False
        if isValidOk and count == 0:
            errMsg = "all empty count Error"
            isValidOk = False
        if (isValidOk and requestParam['maxItem'] < 1):
            errMsg = 'maxItem Error'
            isValidOk = False
        if (isValidOk and requestParam['page'] < 1):
            errMsg = 'page Error'
            isValidOk = False
        return isValidOk, errMsg

    def questionID(self, requestParam):
        # 设置初始验证值
        isValidOk = True
        errMsg = ''
        # 验证用户id必须存在
        question = Question.objects.filter(pk=requestParam['questionId'])
        if isValidOk and (not question.exists()):
            errMsg = 'questionId Error'
            isValidOk = False
        return isValidOk, errMsg

    def myQuestionSearch(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        if isValidOk and (not requestParam['skill'] in ['ALL', 'Listening', 'Speaking', 'Reading', 'Writing']):
            errMsg = "skill Error"
            isValidOk = False
        if isValidOk and (requestParam['skill'] in ['ALL', 'Listening', 'Speaking', 'Reading', 'Writing']):
            if isValidOk and requestParam['skill'] == 'ALL':
                if isValidOk and (not requestParam['questionType'] in ['ALL']):
                    errMsg = "ALL ALL Error"
                    isValidOk = False
            if isValidOk and requestParam['skill'] == 'Writing':
                if isValidOk and (not requestParam['questionType'] in ['ALL', 'SWT', 'WE']):
                    errMsg = "Writing questionType Error"
                    isValidOk = False
            if isValidOk and requestParam['skill'] == 'Reading':
                if isValidOk and (not requestParam['questionType'] in ['ALL', 'RMC(S)', 'RMC', 'RO', 'FIB(R)', 'FIB(W+R)']):
                    errMsg = "Reading questionType Error"
                    isValidOk = False
            if isValidOk and requestParam['skill'] == 'Speaking':
                if isValidOk and (not requestParam['questionType'] in ['ALL', 'RA', 'RS', 'DI', 'RL', 'ASQ']):
                    errMsg = "Speaking questionType Error"
                    isValidOk = False
            if isValidOk and requestParam['skill'] == 'Listening':
                if isValidOk and (not requestParam['questionType'] in ['ALL', 'SST', 'LMC', 'FIB', 'HCS', 'LMCS', 'SMW', 'HIW', 'WFD']):
                    errMsg = "Listening questionType Error"
                    isValidOk = False
        if isValidOk and (not requestParam['state'] in ['全部', '未完成', '已完成', '错题', '收藏']):
            errMsg = "state Error"
            isValidOk = False
        if (isValidOk and requestParam['maxItem'] < 1):
            errMsg = 'maxItem Error'
            isValidOk = False
        if (isValidOk and requestParam['page'] < 1):
            errMsg = 'page Error'
            isValidOk = False
        return isValidOk, errMsg

    def IdentityCheck(self, user, identity):
        if identity == 'student':
            # 设置初始验证值
            isValidOk = True
            errMsg = ''
            student = Student.objects.filter(userInfo=user)
            if isValidOk and (not student.exists()):
                errMsg = 'student not exist'
                isValidOk = False
            return isValidOk, errMsg
        elif identity == 'teacher':
            # 设置初始验证值
            isValidOk = True
            errMsg = ''
            teacher = Teacher.objects.filter(userInfo=user)
            if isValidOk and (not teacher.exists()):
                errMsg = 'teacher not exist'
                isValidOk = False
        elif identity == 'admin':
            # 设置初始验证值
            isValidOk = True
            errMsg = ''
            if user.userType != 'admin':
                errMsg = 'admin not exist'
                isValidOk = False
            return isValidOk, errMsg

    def getMyClass(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        count = 0
        if requestParam['state'] != '':
            count += 1
            if isValidOk and (not requestParam['state'] in ['全部', '未提交', '审核中', '未开课', '已完结']):
                errMsg = "classType Error"
                isValidOk = False
        if isValidOk and (requestParam['startDate'] != '' and requestParam['stopDate'] != ''):
            count += 1
            if isValidOk and (not (requestParam['startDate'] < requestParam['stopDate'])):
                errMsg = "time Error"
                isValidOk = False
        elif isValidOk and (not (requestParam['startDate'] == '' or requestParam['stopDate'] == '')):
            errMsg = "time Error"
            isValidOk = False
        if isValidOk and count == 0:
            errMsg = "all empty count Error"
            isValidOk = False
        if (isValidOk and requestParam['maxItem'] < 1):
            errMsg = 'maxItem Error'
            isValidOk = False
        if (isValidOk and requestParam['page'] < 1):
            errMsg = 'page Error'
            isValidOk = False
        return isValidOk, errMsg

    def WHO(self, user):
        usertype = ''
        student = Student.objects.filter(userInfo=user)
        teacher = Teacher.objects.filter(userInfo=user)
        if student.exists():
            usertype = 'student'
        if teacher.exists():
            usertype = 'teacher'
        return usertype

    def adminClass(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        if requestParam['classState'] != '':
            if isValidOk and (not requestParam['classState'] in ['全部', '待审核', '已驳回', '已上线', '已下线', '已结束']):
                errMsg = "classState Error"
                isValidOk = False
        if isValidOk and (not(requestParam['startDate'] < requestParam['stopDate'])):
            errMsg = "time Error"
            isValidOk = False
        # if isValidOk and (not requestParam['teacherName'] == ''):
        #     count += 1
        #     if isValidOk and requestParam['teacherName'] != '-1':
        #         验证用户id必须存在
                # user = Teacher.objects.filter(pk=requestParam['teacherName'])
                # if isValidOk and (not user.exists()):
                #     errMsg = 'teacherName Error'
                #     isValidOk = False
        if (isValidOk and requestParam['maxItem'] < 1):
            errMsg = 'maxItem Error'
            isValidOk = False
        if (isValidOk and requestParam['page'] < 1):
            errMsg = 'page Error'
            isValidOk = False
        return isValidOk, errMsg

    def classEval(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        if isValidOk and (not requestParam['evalState'] in ['驳回', '上线']):
            errMsg = "evalState Error"
            isValidOk = False
        # 验证onlineClassId必须存在
        onlineClass = OnlineClass.objects.filter(pk=requestParam['classId'])
        if isValidOk and (not onlineClass.exists()):
            errMsg = 'ClassId Error'
            isValidOk = False
        return isValidOk, errMsg

    def classEdit(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        # 验证onlineClassId必须存在
        onlineClass = OnlineClass.objects.filter(pk=requestParam['classId'])
        if isValidOk and (not onlineClass.exists()):
            errMsg = 'onlineClassId Error'
            isValidOk = False
        return isValidOk, errMsg

    def teacherAdmin(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        if isValidOk and (not requestParam['teacherState'] in ['全部', '待审核', '已通过']):
            errMsg = "teacherState Error"
            isValidOk = False
        if (isValidOk and requestParam['maxItem'] < 1):
            errMsg = 'maxItem Error'
            isValidOk = False
        if (isValidOk and requestParam['page'] < 1):
            errMsg = 'page Error'
            isValidOk = False
        return isValidOk, errMsg

    def teacherEval(self, requestParam):
        # 设置初始验证值 [list]
        isValidOk = True
        errMsg = ''
        if isValidOk and (not requestParam['teacherEvalState'] in ['驳回', '通过']):
            errMsg = "teacherEvalState Error"
            isValidOk = False
        # 验证用户id必须存在
        user = Teacher.objects.filter(pk=requestParam['teacherId'])
        if isValidOk and (not user.exists()):
            errMsg = 'teacherId Error'
            isValidOk = False
        return isValidOk, errMsg

class WechatApi:
    def __init__(self):
        self.appid = 'wx90cdb9a270132dff'
        self.appsecret = 'ce8e73297d40cefc70ebd1ff45e48e56'
        self.redirect_uri = '127.0.0.1:3000'

    def getCode(self):
        pdb.set_trace()
        url = 'https://' + self.redirect_uri
        urlencode = url.encode('gb2312')
        redirectUriEncode = quote(urlencode)
        # encodeUrl = urllib.parse.urlencode(self.redirect_uri)
        url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + self.appid + '&redirect_uri=' + redirectUriEncode + '&response_type=code' + '&scope=' + 'snsapi_userinfo' +'&state=STATE'
        result = json.loads(requests.get(url).text)
        return result

    def getAccesstoken(self, code):
        b = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + self.appid + '&secret=' + self.appsecret + '&code=' + code + '&grant_type=authorization_code'
        result = json.loads(requests.get(b).text)
        # print(result, access_token, openid, refresh_token)
        return result

    def refresh(self, refresh_token):
        refresh_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN"
        r_new_url = refresh_url.replace('APPID', self.appid).replace('REFRESH_TOKEN', refresh_token)
        refresh = json.loads(requests.get(r_new_url).text)
        # print(refresh)
        return refresh

    def checkRefresh(self, access_token, openid):
        # 检验授权凭证（access_token）是否有效 access_token	openid
        check_url = 'https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID'
        c_new_url = check_url.replace('ACCESS_TOKEN', access_token).replace('OPENID', openid)
        check = json.loads(requests.get(c_new_url).text)
        print(check)
        return check

    def getPerson(self, access_token, openid):
        # 获取用户个人信息（UnionID机制）access_token	openid
        person_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID"
        p_new_url = person_url.replace('ACCESS_TOKEN', access_token).replace('OPENID', openid)
        personal = json.loads(requests.get(p_new_url).content.decode('utf-8'))
        # print(personal)
        return personal

    def hasSha1(self, sign):
        #对sign进行sha1加密
        s1 = hashlib.sha1()
        s1.update(sign.encode('utf-8'))
        sha1Text = s1.hexdigest()
        return sha1Text







